package com.jinxin.platform.cdperprotypay.controller;

import com.jinxin.platform.base.common.annotation.RegBusiness;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdperprotypay.pojo.vo.ProvideRpcVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 描述类的功能
 *
 * @author su
 * 2020-11-16 15:04
 */
@Slf4j
@RestController
@RequestMapping("/cdpropertypay/business")
public class StockProvideRpcCtr {

    @Autowired
    private ApplicationContext applicationContext;

    @PostMapping("/provide")
    public JsonResult provide(@RequestBody ProvideRpcVo provideRpcVo) {
        log.info("模块提供接口 测试调用数据---->{}", provideRpcVo);

        Class<RegBusiness> annotationClass = RegBusiness.class;
        Map<String, Object> regBusinessAnnotation = this.applicationContext.getBeansWithAnnotation(annotationClass);
        for (Map.Entry<String, Object> entry : regBusinessAnnotation.entrySet()) {
            Object service = entry.getValue();
            Class<?> clazz = AopUtils.getTargetClass(service);
            RegBusiness regBusiness = (RegBusiness) AnnotationUtils.findAnnotation(clazz, RegBusiness.class);
            if (regBusiness.moduleKey().equals(provideRpcVo.getModuleKey()) &&
                    regBusiness.className().equals(provideRpcVo.getClassName())) {
                Method method = ReflectionUtils.findMethod(service.getClass(), provideRpcVo.getFunName(), new Class[]{Map.class});
                if (method == null) {
                    return JsonResult.error("未找到注册的提供方法");
                } else {
                    method.setAccessible(true);
                    Object[] params = new Object[]{provideRpcVo.getParams()};
                    Object back = ReflectionUtils.invokeMethod(method, service, params);
                    if (!(back instanceof JsonResult)) {
                        back = JsonResult.ok(back);
                    }
                    JsonResult result = (JsonResult) back;
                    return result;
                }
            } else {
                return JsonResult.error("无法获取调用服务,请检查参数");
            }
        }

        return JsonResult.error("无法获取调用服务,请检查参数");
    }
}
